﻿
Public Class indexedJob
    Private Shared ReadOnly INDEXEDJOB_CTOR_TO_CHECKOUT_TIMEMS As Int64
    Private Shared ReadOnly INDEXEDJOB_CHECKOUT_TO_FINISH_TIMEMS As Int64
    Public [end] As void = Nothing
    Private ReadOnly _ctorMs As Int64
    Private ReadOnly _job As ijob
    Private _checkOutMs As Int64
    Private _finishMs As Int64
    Private _index As Int64
    Private _canceled As Boolean = False
    Private _finished As Boolean = False

    Shared Sub New()
        INDEXEDJOB_CTOR_TO_CHECKOUT_TIMEMS = counter.registerAverageAndLastAverage("INDEXEDJOB_CTOR_TO_CHECKOUT_TIMEMS")
        INDEXEDJOB_CHECKOUT_TO_FINISH_TIMEMS =
            counter.registerAverageAndLastAverage("INDEXEDJOB_CHECKOUT_TO_FINISH_TIMEMS")
    End Sub

    Public Sub checkOut()
        _checkOutMs = Now.milliseconds()
    End Sub

    Public Function ctorMs() As Int64
        assert(_ctorMs <> 0)
        Return _ctorMs
    End Function

    Public Function checkOutMs() As Int64
        If _checkOutMs = 0 Then
            checkOut()
        End If
        Return _checkOutMs
    End Function

    Public Function finishMs() As Int64
        assert(_finishMs <> 0)
        Return _finishMs
    End Function

    Public Function job() As ijob
        assert(Not _job Is Nothing)
        Return _job
    End Function

    Public Sub finish()
        _finished = True
        _end()
    End Sub

    Public Function finished() As Boolean
        Return _finished
    End Function

    Public Sub cancel()
        _canceled = True
        _end()
    End Sub

    Public Function canceled() As Boolean
        Return _canceled
    End Function

    Private Sub _end()
        _finishMs = Now.milliseconds()
        'to avoid be called twice
        If canceled() OrElse finished() Then
            threadpoolRun([end])
        End If

        counter.increase(INDEXEDJOB_CTOR_TO_CHECKOUT_TIMEMS, checkOutMs() - ctorMs())
        counter.increase(INDEXEDJOB_CHECKOUT_TO_FINISH_TIMEMS, finishMs() - checkOutMs())
    End Sub

    Friend Sub New(ByVal index As Int64, ByVal job As ijob)
        assert(Not job Is Nothing)
        _index = index
        _job = job
        _ctorMs = Now.milliseconds()
    End Sub

    Public Function index() As Int64
        Return _index
    End Function

    Public NotOverridable Overrides Function GetHashCode() As Int32
        Return job().GetHashCode()
    End Function
End Class
